<template>
    <div class="addproductPage">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm"   label-width="100px" class="demo-ruleForm" :disabled="isDetail" >
            <div class="basic-info" style="margin-top: 20px;">基本信息</div> 
            
      <el-form-item label="产品分类" prop="categoryId" >
        <el-select
          @change="selectOrigin2"
          size="small"
          clearable
          v-model="ruleForm.categoryId"
          placeholder="请选择"
        >
          <el-option
            v-for="item in List2"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :disabled="item.disabled"
          ></el-option>
        </el-select>
      </el-form-item>



            <el-form-item label="产品类型" prop="type" >
                <el-radio-group v-model="ruleForm.type"  >
                    <el-radio :label="0" >虚拟</el-radio>
                    <el-radio :label="1" >实物</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="产品编码" prop="goodId" required  placeholder="请填写SPU编码，来自于泰康之家/泰康拜博">
                <el-input v-model="ruleForm.goodId"></el-input>
            </el-form-item>
            <el-form-item label="产品名称" prop="goodName" required  placeholder="请填写名称">
                <el-input v-model="ruleForm.goodName"  style="width:500px;" maxlength="30"></el-input>
            </el-form-item>
            <el-form-item label="产品来源" prop="channel" required  >
                <el-select v-model="ruleForm.channel" placeholder="请选择(拜博/健投)">
                <el-option label="建投" value="A"></el-option>
                <el-option label="拜博" value="B"></el-option>
                </el-select>
            </el-form-item>

              <!-- <el-form-item label="商品图片">
            <el-upload
                class="avatar-uploader"
                :action="baseUrl + '/v1/addimg/food'"
                :show-file-list="false"
                :on-success="uploadImg"
                :before-upload="beforeImgUpload">
                <img v-if="foodForm.image_path" :src="baseImgPath + foodForm.image_path" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item> -->

      <!-- </el-col>
          <el-col style="text-align:center" :span="14">
            <img :hidden="isUpd" :src="img" alt />
          </el-col>
        </el-row> -->
      <el-form-item label="产品图片" prop="pic" width="120">
          
        <template slot-scope="scope">
          <img :src="ruleForm.pic" />
        </template>
      </el-form-item>

      <div class="basic-info">产品信息</div>

      <el-form-item
        label="产品描述"
        prop="description"
        style="margin-top: 20px"
      >
        <el-input v-model="ruleForm.description"></el-input>
      </el-form-item>
      <el-form-item label="产品现价" prop="marketPrice" required>
        <el-input v-model="ruleForm.marketPrice / 100"></el-input>
      </el-form-item>
      <el-form-item label="划线价" prop="originalPrice">
        <el-input v-model="ruleForm.originalPrice / 100"></el-input>
      </el-form-item>
      <el-form-item label="产品链接" prop="url" required>
        <el-input v-model="ruleForm.url"></el-input>
      </el-form-item>

      <div class="More-settings">更多设置</div>

      <el-form-item label="产品排序" prop="showOrder">
        <el-input v-model="ruleForm.showOrder"></el-input>
      </el-form-item>
      <el-form-item label="上架设置" prop="goodStatus">
        <el-radio-group v-model="ruleForm.goodStatus">
          <el-radio :label="0">立即上架</el-radio>
          <el-radio :label="2">定时上架</el-radio>
          <el-date-picker
            style="width: 250px"
            v-model="ruleForm.showShelfTime"
            @change="timechange1"
            format="yyyy-M-dd h:mm:ss"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
          <el-radio :label="1" style="margin-left: 20px">暂不上架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="下架设置" prop="godown">
        <el-checkbox-group v-model="ruleForm.godown">
          <el-checkbox label="5" style="margin-right: 20px"
            >定时下架</el-checkbox
          >
          <el-date-picker
            @change="timechange2"
            v-model="ruleForm.offShelfTime"
            type="date"
            format="yyyy-M-dd h:mm:ss"
            placeholder="下架日期"
          >
          </el-date-picker>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="活动标签" prop="label">
        <el-select
          @change="selectOrigin1"
          size="small"
          clearable
          v-model="ruleForm.label"
          placeholder="请选择"
        >
          <el-option
            v-for="item in List"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

        <el-form-item label="产品标签">
            <el-tag
            :key="index"
            v-for="(tag,index) in dynamicTags"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-autocomplete
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            :popper-append-to-body="false"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @select="handleSelect"
            @keyup.enter.native="handleInputConfirm"
            @input="change"
          >
          </el-autocomplete>
          <el-button v-else class="button-new-tag" size="small" @click="showInput"
            >+ 新标签</el-button
          >
      </el-form-item>
   
      <el-form-item label='是否推广' prop="promotion">
        <el-radio-group v-model="ruleForm.promotion" @change="select2">
          <el-radio :label="0">是</el-radio>
          <el-radio :label="1">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <!-- <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button> -->
        <el-button @click="resetForm('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import goodsApi from "@/api/lejv/goods"
// import setting from "@/settings"
import {queryGoodsdetail} from "@/api/lejv/goods"
  export default {
    data () {
        var validatemarketPrice = (rule, value, callback) => {
        if (!value) {   
          callback(new Error('请填写现价'));
        } else {
          // if (value >= this.ruleForm.originalPrice){

        //   callback(new Error('划线价低于原价，请重新输入'));
        // }
        callback();
      }
    };
    var validateoriginalPrice = (rule, value, callback) => {
      if (!value) {
        callback();
      } else {
        if (value <= this.ruleForm.marketPrice) {
          callback(new Error("划线价低于原价，请重新输入"));
        }
        callback();
      }
    };
    var checkUrl = (rule, value, callback) => {
      //自定义校验规则,验证网址是否输入正确
      //       if (this.ruleForm.url !== "") {
      //         let reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/;
      //         if (!reg.test(this.ruleForm.url)) {
      //           callback(new Error("请输入正确的网址!"));
      //         } else {
      //           callback();
      //         }
      //       } else {
      //         callback();
      //       }
      if (this.ruleForm.url !== "") {
        let reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])/;
        if (!reg.test(this.ruleForm.url)) {
          return callback(new Error("请输入以http/https开头的网址!"));
        }
        callback();
      }
    };
    return {
      baseUrl: "",
      radio: "1",
      img:"",
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      restaurants: [],
      label:"",
      ruleForm: {
        type: "",
        goodId: "", //编码
        goodName: "",
        channel: "",
        description: "",
        originalPrice: "",
        marketPrice: "",
        url: "",
        goodStatus: "",
        pic: "",
        showShelfTime: "",
        offShelfTime: "",
        label: "",
        godown: "",
        categoryId:'',
        promotion:'',
        labelType:" 0",
        shelfLabelDataList:[]
      },
      rules: {
        goodId: [
          {
            required: true,
            message: "请填写SPU编码，来自于泰康之家",
            trigger: "blur",
          },
        ],
        goodName: [
          {
            required: true,
            min: 2,
            max: 60,
            message: "请填写产品名称",
            trigger: "blur",
          },
        ],
        categoryId:[
                  { required: true, message: "请选择产品分类", trigger: "change" },
                ],
        channel: [
          { required: true, message: "请选择建投或拜博", trigger: "blur" },
        ],
        marketPrice: [
          // { required: true, message: "请保留小数点后2位", trigger: "blur" },
          { validator: validatemarketPrice, required: true, trigger: "blur" },
        ],
        originalPrice: [
          // { message: "划线价低于原价,请重新输入", trigger: "blur" },
          { validator: validateoriginalPrice, trigger: "blur" },
        ],
        url: [
          {
            required: true,
            validator: checkUrl,
            message: "请填写http,https开头的产品链接",
            trigger: "blur",
          },
        ],
      },
        placeList: [
        {
          value: "B",
          label: "拜博",
        },
        {
          value: "A",
          label: "健投",
        },
      ],
      List: [
        // { value: "0", label: "新品" },
        // { value: "1", label: "促销" },
        // { value: "2", label: "特价" },
        // { value: "3", label: "限时" },
        // { value: "4", label: "秒杀" },
      ],
       List2: [
        // { value: "养康", 
        //  label: "养康" ,
         
        // },
        // { value: "齿科", 
        //   label: "齿科" 
        // },
        // { value: "体检", 
        //   label: "体检" ,
        //   disabled: true
        // },
        // { value: "保险", 
        //   label: "保险",
        //   disabled: true
        // },
        // { value: "其他", 
        //   label: "其他",
        //   disabled: true
        // },
      ],
      options: [
        {
          value: "A",
          label: "健投",
        },
        {
          value: "B",
          label: "拜博",
        },
      ],
      value: "",
      value1: "",
      isDetail: true,
      id: "",
      isUpd: true, //隐藏图片
      dialogFormVisible: false,
      foodForm: {
        image_path: "",
        name: "",
        description: "",
      },
    };
  },
  created() {
    this.id = this.$route.params.detailid;
    console.log(this.$route.params.detailid);
    this.init();
    if (this.$route.params.detailid) {
      this.isDetail = true;
    } else {
    }
    this.getlabel()
    this.getcategories()
  },
  methods: {

      //产品标签接口
    getlabel(){
      goodsApi.getlabel(0).then(res=>{
        console.log(res.data)
        if(res.code == 0){
            console.log(res.data)
           this.List=res.data.map(item=>({
             value:item.id,
             label:item.labelName
           }))
          console.log(this.List)
        }
      }

      )

    },
     // 产品分类接口
    getcategories(){
      goodsApi.getcategories().then(res=>{
        console.log(res)
        if(res.code== 0){
           console.log(res.data)
           this.List2=res.data.map(item=>({
             value:item.id,
             label:item.categoryName
           }))
            console.log(this.List2)
            }
        }
          )
    },
     //推荐标签模糊查询
    getquery(name){
      let obj={
        labelType:"1",
        labelName: name
      }
      console.log(this.inputValue)
      if(this.inputValue){
        goodsApi.getquery(obj).then(res=>{
        if(res.data){
          this.restaurants=res.data.map(item=>({
              value:item.labelName,
              id:item.id
              }))
        }

        console.log(res)
     })
      }
      
    },
     change(){
      if(this.timeout) {
        clearTimeout(this.timeout)
      }
      // wait = 800 为设定的时间, 可以根据需求指定
      this.timeout = setTimeout(() => {
        // 调用接口 处理逻辑
        this.getquery(this.inputValue)
      },800)

    },
    //调查看接口
    init() {
      console.log(this.id);
      // let str = '?id='+this.id
      goodsApi.queryGoodsdetail(this.$route.params.detailid).then((res) => {
        if (res.code == 0) {
          this.ruleForm.type = Number(res.data.type);
          this.ruleForm.goodId = res.data.goodId;
          this.ruleForm.goodName = res.data.goodName;
          this.ruleForm.channel = res.data.channel;
          this.ruleForm.description = res.data.description;
          this.ruleForm.originalPrice = res.data.originalPrice;
          this.ruleForm.marketPrice = res.data.marketPrice;
          this.ruleForm.url = res.data.url;
          this.ruleForm.showOrder = res.data.showOrder;
          this.ruleForm.goodStatus = Number(res.data.goodStatus);
          this.ruleForm.label = res.data.label;
          this.ruleForm.showShelfTime = res.data.showShelfTime;
          this.ruleForm.offShelfTime = res.data.offShelfTime;
          this.ruleForm.pic = res.data.pic;
          this.ruleForm.categoryId = res.data.categoryId;
          this.ruleForm.promotion = res.data.promotion;
          this.ruleForm.labelType = res.data.labelType;
          this.ruleForm.shelfLabelDataList=res.data.shelfLabelDataList
          if (this.ruleForm.offShelfTime) {
            this.ruleForm.godown = ["5"];
          }
        }
          this.ruleForm.category=res.data.category
          let a= this.ruleForm.shelfLabelDataList.find(item=>
                        item.labelType=='0',
                        
                    )
                      let b= this.ruleForm.shelfLabelDataList.filter(item=>
                        item.labelType=='1',
                        
                    )
                    if(a){
                      this.label = a.labelName
                    }
                    if(b){
                      b.forEach(item=>{
                        this.dynamicTags.push(item.labelName)
                      })
                    console.log(this.ruleForm.shelfLabelDataList,b, this.dynamicTags)
                    }
        console.log(this.ruleForm.pic);
      });
    },
     //产品标签接口
    getlabel(){

      goodsApi.getlabel(0).then(res=>{
        console.log(res.data)
        if(res.code == 0){
            console.log(res.data)
           this.List=res.data.map(item=>({
             value:item.id,
             label:item.labelName
           }))
          console.log(this.List)
        }
      }

      )

    },
      // 产品分类接口
    getcategories(){

      goodsApi.getcategories().then(res=>{
        console.log(res)
        if(res.code== 0){
           console.log(res.data)
           this.List2=res.data.map(item=>({
             value:item.id,
             label:item.categoryName
           }))
            console.log(this.List2)
            }
        }
          )
    },
    //选择来源
    selectOrigin(val) {
      console.log(val);
      this.ruleForm.channel = val;
    },
    selectOrigin1(val) {
       let index=this.List.findIndex(item=>
            item.value==val
            )
            this.ruleForm.label = this.List[index].label;
            // console.log(val,this.List,index);
            let obj ={
              labelType:"0",
              labelName:this.List[index].label,
              id:val
            }
            this.ruleForm.shelfLabelDataList.push(obj)
            console.log(this.ruleForm.shelfLabelDataList);
    },
    selectOrigin2(val) {
      this.ruleForm.categoryId = val;
      console.log(val);
    },
     handleClose(tag) {

      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      this.ruleForm.shelfLabelDataList = this.ruleForm.shelfLabelDataList.filter(item => item.labelName != tag)
      console.log("000,",this.dynamicTags,tag,this.ruleForm.shelfLabelDataList)
    // this.dynamicTags.remove(this.dynamicTags.indexOf(tag));
      },
    showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
     handleInputConfirm() {
        // let inputValue = this.inputValue;
        let obj=null
        if (this.inputValue) {
          this.dynamicTags.push(this.inputValue);
          obj={
            labelName:this.inputValue,
            labelType:"1"
          };
          if(this.ruleForm.labelId){
            obj.id = this.ruleForm.labelId
            this.ruleForm.labelId=""
          }
          this.ruleForm.shelfLabelDataList.push(obj)
        }
        this.inputVisible = false;
        this.inputValue = '';
        console.log(this.dynamicTags,this.ruleForm.shelfLabelDataList)

          this.getquery(this.dynamicTags[this.dynamicTags.length-1])


      },
     querySearch(queryString, cb) {
        var restaurants = this.restaurants;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
       handleSelect(event) {
        console.log(event,this.ruleForm.shelfLabelDataList);
        this.ruleForm.labelId = event.id
        this.handleInputConfirm()
      },
    select2(val) {
      this.ruleForm.promotion = val;
      console.log(val);
    },
    timechange1: function (val) {
      console.log(val);
      this.form.showShelfTime = val;
      console.log(this.form.showShelfTime);
    },
    timechange2: function (val) {
      console.log(val);
      this.form.offShelfTime = val;
      console.log(this.form.offShelfTime);
    },
    resetForm(formName) {
      this.$router.push("/goods/kind");
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$router.push("/goods/kind");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
.addproductPage {
  padding-left: 20px;
}
.product-mode {
  padding-top: 15px;
  padding-bottom: 15px;
  margin-bottom: 30px;
  border-bottom: 1px solid lightgrey;
  span {
    height: 10px;
    padding-top: 150px;
  }
}
.basic-info {
  background: rgb(228, 228, 228);
  padding-left: 30px;
  padding-top: 10px;
  padding-right: 30px;
  padding-bottom: 10px;
  margin-bottom: 10px;
}
.product-type {
  margin-top: 20px;
  display: flex;
  .el-button {
    background: white;
    color: black;
    margin-right: 40px;
  }
}
.el-input {
  width: 300px;
}
.More-settings {
  background: rgb(228, 228, 228);
  padding-left: 30px;
  padding-top: 10px;
  padding-right: 30px;
  padding-bottom: 10px;
  margin-bottom: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  border: 1px solid black;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
}
img {
  width: 60px;
  height: 60px;
}
</style>
